package com.zrwl.poscloud.core.restapi.admin.baseInfo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.zrwl.poscloud.base.entity.*;
import com.zrwl.poscloud.core.annotion.AuthorityVerify.AuthorityVerify;
import com.zrwl.poscloud.core.annotion.OperationLogger.OperationLogger;
//import com.zrwl.poscloud.core.global.DeptDataStatic;
import com.zrwl.poscloud.commons.exception.ThrowableUtils;
import com.zrwl.poscloud.commons.utils.JsonUtils;
import com.zrwl.poscloud.commons.utils.ResultUtil;
import com.zrwl.poscloud.commons.utils.StringUtils;
import com.zrwl.poscloud.commons.validator.group.Delete;
import com.zrwl.poscloud.commons.validator.group.GetList;
import com.zrwl.poscloud.commons.validator.group.Insert;
import com.zrwl.poscloud.commons.validator.group.Update;
import com.zrwl.poscloud.xo.mapper.SysDictDataMapper;
import com.zrwl.poscloud.xo.service.*;
import com.zrwl.poscloud.xo.vo.AdminVO;
import com.zrwl.poscloud.xo.vo.DeptVO;
import com.zrwl.poscloud.xo.vo.ImportDetailVO;
import com.zrwl.poscloud.xo.vo.SysDictDataVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * 导入明细 controller api类
 *
 * @author 刘思童 AutoGenerate
 * @date 2021-11-02
 */
@RestController
@Api(value = "导入明细相关接口", tags = {"导入明细相关接口"})
@RequestMapping("/importDetail")
@Slf4j
public class ImportDetailRestApi {
    @Autowired
    private ImportBatchService importBatchService;
    @Autowired
    private ImportDetailService importDetailService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private AdminLogService adminLogService;
//    @Autowired
//    private ComCardRecordService comCardRecordService;
    @Autowired
    private DeptAdminRService deptAdminRService;
    @Autowired
    private CompanyDictDataService companyDictDataService;
    @Autowired
    private SysDictDataService sysDictDataService;
    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @AuthorityVerify
    @ApiOperation(value = "获取导入明细列表", notes = "获取导入明细列表", response = String.class)
    @PostMapping("/getList")
    public String getList(@Validated({GetList.class}) @RequestBody ImportDetailVO importDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("获取导入明细列表: {}", importDetailVO);
        AdminVO adminVO = adminService.getMe();
        if (!adminVO.isCompany()) {
            return ResultUtil.errorWithMessage("仅商户用户支持此功能");
        }
        importDetailVO.setDeptRoleTree(deptAdminRService.getMyDeptRoleTreeName());
        return ResultUtil.successWithData(importDetailService.getPageList(importDetailVO));
    }

    @AuthorityVerify
    @ApiOperation(value = "获取导入明细列表", notes = "获取导入明细列表", response = String.class)
    @PostMapping("/getAllList")
    public String getAllList(@Validated({GetList.class}) @RequestBody ImportDetailVO importDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("获取导入明细列表: {}", importDetailVO);
        return ResultUtil.successWithData(importDetailService.getAllList(importDetailVO));
    }

    @AuthorityVerify
    @OperationLogger(value = "新增导入明细")
    @ApiOperation(value = "新增导入明细", notes = "新增导入明细", response = String.class)
    @PostMapping("/add")
    public String add(@Validated({Insert.class}) @RequestBody ImportDetailVO importDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("新增导入明细: {}", importDetailVO);
        //1获取当前操作员和字典内容
        AdminVO adminVO = adminService.getMe();
        if (!adminVO.isCompany()) {
            return ResultUtil.errorWithMessage("仅商户用户支持此功能");
        }
        List<CompanyDictData> payLevelList = JsonUtils.jsonToList(JsonUtils.objectToJson(companyDictDataService.getListByCompanyDictType("employee_pay_level", adminVO.getCompanyUid()).get("list")), CompanyDictData.class);
        List<SysDictData> cardTypeList = JsonUtils.jsonToList(JsonUtils.objectToJson(sysDictDataService.getListByDictType("card_type").get("list")), SysDictData.class);
        Map<String, DeptVO> deptRoleTreeEntity = deptAdminRService.getMyDeptRoleTreeEntity(adminVO.getCompanyUid(), adminVO.getUid());
        if (importDetailVO.getBatchUid().isEmpty() || importDetailVO.getBatchUid().trim().isEmpty()) {
            throw new RuntimeException("该条数据不合法");
        }
        Map<String, Object> certCodeSuccessCertMap = new HashMap<String, Object>();
        Map<String, Object> employeeCodeSuccessCertMap = new HashMap<String, Object>();
        Map<String, Object> deptSuccessCertMap = new HashMap<String, Object>();
        ImportBatch importBatch = importBatchService.getById(importDetailVO.getBatchUid());
        //将批次的列配置图进行转换
        Map<String, String> columnConfigMap = JSONObject.parseObject(importBatch.getColumnConfig(), LinkedHashMap.class, Feature.OrderedField);//按序排列
        List<CompanyBusinessFeeConfig> feeConfigList = JSONArray.parseArray(importBatch.getParam(), CompanyBusinessFeeConfig.class);


        ImportDetailVO detailVO = importDetailService.singleImport(columnConfigMap, feeConfigList, payLevelList, cardTypeList, importBatch, importDetailVO, adminVO, certCodeSuccessCertMap, employeeCodeSuccessCertMap, deptRoleTreeEntity, deptSuccessCertMap);
        if (detailVO.getStatus() == 2) {
            throw new RuntimeException(detailVO.getSummary());
        }
        return ResultUtil.successWithMessage("单条导入成功");
    }

    @AuthorityVerify
    @OperationLogger(value = "修改导入明细")
    @ApiOperation(value = "修改导入明细", notes = "修改导入明细", response = String.class)
    @PostMapping("/edit")
    public String edit(@Validated({Update.class}) @RequestBody ImportDetailVO importDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("修改导入明细: {}", importDetailVO);
        //1获取当前操作员和字典内容
        AdminVO adminVO = adminService.getMe();
        if (!adminVO.isCompany()) {
            return ResultUtil.errorWithMessage("仅商户用户支持此功能");
        }
        List<CompanyDictData> payLevelList = JsonUtils.jsonToList(JsonUtils.objectToJson(companyDictDataService.getListByCompanyDictType("employee_pay_level", adminVO.getCompanyUid()).get("list")), CompanyDictData.class);
        List<SysDictData> cardTypeList = JsonUtils.jsonToList(JsonUtils.objectToJson(sysDictDataService.getListByDictType("card_type").get("list")), SysDictData.class);
        Map<String, DeptVO> deptRoleTreeEntity = deptAdminRService.getMyDeptRoleTreeEntity(adminVO.getCompanyUid(), adminVO.getUid());
        if (importDetailVO.getBatchUid().isEmpty() || importDetailVO.getBatchUid().trim().isEmpty()) {
            throw new RuntimeException("该条数据不合法");
        }
        Map<String, Object> certCodeSuccessCertMap = new HashMap<String, Object>();
        Map<String, Object> employeeCodeSuccessCertMap = new HashMap<String, Object>();
        Map<String, Object> deptSuccessCertMap = new HashMap<String, Object>();
        ImportBatch importBatch = importBatchService.getById(importDetailVO.getBatchUid());
        //将批次的列配置图进行转换
        Map<String, String> columnConfigMap = JSONObject.parseObject(importBatch.getColumnConfig(), LinkedHashMap.class, Feature.OrderedField);//按序排列
        List<CompanyBusinessFeeConfig> feeConfigList = JSONArray.parseArray(importBatch.getParam(), CompanyBusinessFeeConfig.class);
        ImportDetailVO detailVO = importDetailService.singleImport(columnConfigMap, feeConfigList, payLevelList, cardTypeList, importBatch, importDetailVO, adminVO, certCodeSuccessCertMap, employeeCodeSuccessCertMap, deptRoleTreeEntity, deptSuccessCertMap);
        if (detailVO.getStatus() == 2) {
            throw new RuntimeException(detailVO.getSummary());
        }
        return ResultUtil.successWithMessage("修改成功");
    }

    @AuthorityVerify
    @OperationLogger(value = "删除导入明细")
    @ApiOperation(value = "删除导入明细", notes = "删除导入明细", response = String.class)
    @PostMapping("/delete")
    public String delete(@Validated({Delete.class}) @RequestBody ImportDetailVO importDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("删除导入明细: {}", importDetailVO);
        return importDetailService.delete(importDetailVO);
    }

    @AuthorityVerify
    @OperationLogger(value = "导入明细")
    @ApiOperation(value = "导入明细", notes = "导入明细", response = String.class)
    @PostMapping("/importList")
    public String importList(@Validated({Insert.class}) @RequestBody ImportDetailVO importDetailVO, BindingResult result) {
        log.info("导入明细: {}", importDetailVO);
        List<ImportDetail> allList = importDetailService.getAllList(importDetailVO);
        return ResultUtil.errorWithMessage("导入成功");
    }
    @AuthorityVerify
    @ApiOperation(value = "获取下载模板数据", notes = "获取下载模板数据", response = String.class)
    @PostMapping("/downloadTemplateData")
    public String downloadTemplateData(@Validated({GetList.class}) @RequestBody ImportDetailVO importDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("获取下载模板数据: {}", importDetailVO);
        AdminVO adminVO = adminService.getMe();
        if (!adminVO.isCompany()) {
            return ResultUtil.errorWithMessage("仅商户用户支持此功能");
        }
        if (StringUtils.isEmpty(importDetailVO.getCompanyCode()) || StringUtils.isEmpty(importDetailVO.getCompanyCode().trim())) {
            importDetailVO.setCompanyCode(adminVO.getCompanyCode());
        }
        return ResultUtil.successWithData(importDetailService.downloadTemplateData(importDetailVO));
    }
}
